package com.lc.pianostudent.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.joker.annotation.PermissionsCustomRationale;
import com.joker.annotation.PermissionsDenied;
import com.joker.annotation.PermissionsGranted;
import com.joker.annotation.PermissionsNonRationale;
import com.joker.annotation.PermissionsRequestSync;
import com.joker.api.Permissions4M;
import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.conn.PostActionAction;
import com.lc.pianostudent.conn.PostGetCode;
import com.lc.pianostudent.conn.PostLogintype;
import com.lc.pianostudent.dialog.BeginDialog;
import com.lc.pianostudent.dialog.ShopDialog;
import com.lc.pianostudent.dialog.VipDialog;
import com.lc.pianostudent.fragment.ContactFragment;
import com.lc.pianostudent.fragment.FindFragment;
import com.lc.pianostudent.fragment.HomeFragment;
import com.lc.pianostudent.fragment.MineFragment;
import com.zcx.helper.app.AppCallBack;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by Administrator on 2016/3/14.普通用户
 */

public class NavigationActivity extends BaseActivity implements View.OnClickListener{
    private TimerTask timerTask = null;
    private Timer timer = null;
    private boolean isExit = false;

    @BoundView(R.id.img_navigation_home)
    private ImageView img_navigation_home;//首页
    @BoundView(R.id.img_navigation_product)
    private ImageView img_navigation_product;//产品
    @BoundView(R.id.img_navigation_integral)
    private ImageView img_navigation_integral;//积分
    @BoundView(R.id.img_navigation_mine)
    private ImageView img_navigation_mine;//我的

    @BoundView(R.id.tv_navigation_home)
    private TextView tv_navigation_home;
    @BoundView(R.id.tv_navigation_product)
    private TextView tv_navigation_product;
    @BoundView(R.id.tv_navigation_integral)
    private TextView tv_navigation_integral;
    @BoundView(R.id.tv_navigation_mine)
    private TextView tv_navigation_mine;

    @BoundView(R.id.rl_navigation_home)
    private RelativeLayout rl_navigation_home;
    @BoundView(R.id.rl_navigation_product)
    private RelativeLayout rl_navigation_product;
    @BoundView(R.id.rl_navigation_integral)
    private RelativeLayout rl_navigation_integral;
    @BoundView(R.id.rl_navigation_mine)
    private RelativeLayout rl_navigation_mine;

    private HomeFragment homeFragment;
    private ContactFragment contactFragment;
    private FindFragment findFragment;
    private MineFragment mineFragment;

    private Fragment[] fragments;

    private int index;
    private int currentTabIndex;
    private static final int AUDIO_CODE = 6;
    private static final int CAMERA_CODE = 7;
    public static OnClickProduct onClickProduct;
    private VipDialog vipDialog ;

    private Handler mHandlerUI = new Handler() {
        public void handleMessage(Message msg) {

            onClick(rl_navigation_product);
        }
    };

    //过期弹窗
    public PostLogintype postLogintype = new PostLogintype(new AsyCallBack<PostLogintype.PostLogintypeInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostLogintype.PostLogintypeInfo postLogintypeInfo) throws Exception {

                if(toast.equals("账号状态正常")){
                    BaseApplication.BasePreferences.saveChoose("2");
                    postActionAction.user_id = BaseApplication.BasePreferences.readUID();
                    postActionAction.execute();
                }else {
                    BaseApplication.BasePreferences.saveChoose("1");
                    Log.e("=====jy","111111");
                    vipDialog = new VipDialog(context, R.layout.ask_vip_popup) {

                        @Override
                        public void cancel() {
                            BaseApplication.BasePreferences.setIsLogin(false);
//                        BaseApplication.BasePreferences.setIsLogin(false);
                            BaseApplication.INSTANCE.finishAllActivity();
                        }

                        @Override
                        public void confirm() {
//                        BaseApplication.BasePreferences.setIsLogin(false);

                            startActivity(new Intent(NavigationActivity.this,VipActivity.class).putExtra("from","1"));
                        }
                    };

                    vipDialog.show();
                }


        }

        @Override
        public void onFail(String toast, int type) throws Exception {
//            BaseApplication.BasePreferences.saveChoose("1");
//            Log.e("=====jy","111111");
//            vipDialog = new VipDialog(context, R.layout.ask_vip_popup) {
//
//                @Override
//                public void cancel() {
//                    BaseApplication.BasePreferences.setIsLogin(false);
////                        BaseApplication.BasePreferences.setIsLogin(false);
//                    BaseApplication.INSTANCE.finishAllActivity();
//                }
//
//                @Override
//                public void confirm() {
////                        BaseApplication.BasePreferences.setIsLogin(false);
//
//                    startActivity(new Intent(NavigationActivity.this,VipActivity.class).putExtra("from","1"));
//                }
//            };
//
//            vipDialog.show();
        }
    });

    //练琴弹窗
    public PostActionAction postActionAction = new PostActionAction(new AsyCallBack<PostActionAction.PostActionActionInfo>(){


        @Override
        public void onSuccess(String toast, int type, Object o, PostActionAction.PostActionActionInfo postActionActionInfo) throws Exception {
//            Log.e("-------",postActionActionInfo.check+"====");
            if(postActionActionInfo.check.equals("true")){
                new BeginDialog(context, R.layout.begin_popup,postActionActionInfo.time,postActionActionInfo.number,postActionActionInfo.xx,postActionActionInfo.wealth,postActionActionInfo.renzhen,postActionActionInfo.zhixing) {

                    @Override
                    public void confirm() {

//                        finish();
                    }
                }.show();
            }else {

            }

        }


        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_navigation);
//        requestPermission();
        setAppCallBack(new CallBack());
        requestPermission();
        requestCameraPermission();
        homeFragment = new HomeFragment();
        contactFragment = new ContactFragment();
        findFragment = new FindFragment();
        mineFragment = new MineFragment();

        fragments = new Fragment[]{homeFragment, contactFragment, findFragment, mineFragment};

        getSupportFragmentManager().beginTransaction().add(R.id.navigation_content, homeFragment)
                .show(homeFragment).commit();

        onClick(rl_navigation_home);

        onClickProduct = new OnClickProduct() {
            @Override
            public void setOnClick() {

                onClick(rl_navigation_home);

            }

            @Override
            public void setOnClickMine() {

                onClick(rl_navigation_mine);

            }

            @Override
            public void remove() {

                Message msg = new Message();
                mHandlerUI.sendMessage(msg);


            }
        };

        if(BaseApplication.BasePreferences.getIsLogin()){
            postLogintype.user_id = BaseApplication.BasePreferences.readUID();
            postLogintype.execute(NavigationActivity.this,false,1);
        }

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.rl_navigation_home:

                index = 0;
                LoginActivity.StartVerifyActivity(new LoginActivity.VerifyCallBack() {

                    @Override
                    public void onCallBack() {
                        if (currentTabIndex != index) {

                            img_navigation_home.setImageResource(R.mipmap.index_icon_01_checked);
                            img_navigation_product.setImageResource(R.mipmap.index_icon_02);
                            img_navigation_integral.setImageResource(R.mipmap.index_icon_03);
                            img_navigation_mine.setImageResource(R.mipmap.index_icon_04);

                            tv_navigation_home.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlue_00a8f3));
                            tv_navigation_product.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_integral.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_mine.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));

                            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                            trx.hide(fragments[currentTabIndex]);
                            if (!fragments[index].isAdded()) {
                                trx.add(R.id.navigation_content, fragments[index]);
                            }
                            //                    trx.show(fragments[index]).commit();
                            trx.show(fragments[index]).commitAllowingStateLoss();
                            currentTabIndex = index;

                        }
                    }

                });

                try {
                    ((HomeFragment.CallBack)getAppCallBack(HomeFragment.class)).onRefresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;

            case R.id.rl_navigation_product:

                index = 1;
                LoginActivity.StartVerifyActivity(new LoginActivity.VerifyCallBack() {

                    @Override
                    public void onCallBack() {
                        if (currentTabIndex != index) {

                            img_navigation_home.setImageResource(R.mipmap.index_icon_01);
                            img_navigation_product.setImageResource(R.mipmap.index_icon_02_checked);
                            img_navigation_integral.setImageResource(R.mipmap.index_icon_03);
                            img_navigation_mine.setImageResource(R.mipmap.index_icon_04);

                            tv_navigation_home.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_product.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlue_00a8f3));
                            tv_navigation_integral.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_mine.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));

                            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                            trx.hide(fragments[currentTabIndex]);
                            if (!fragments[index].isAdded()) {
                                trx.add(R.id.navigation_content, fragments[index]);
                            }
                            trx.show(fragments[index]).commitAllowingStateLoss();

                            currentTabIndex = index;

                        }
                    }

                });
                try {
                    ((ContactFragment.CallBack)getAppCallBack(ContactFragment.class)).onRefresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;

            case R.id.rl_navigation_integral:

                index = 2;
                LoginActivity.StartVerifyActivity(new LoginActivity.VerifyCallBack() {

                    @Override
                    public void onCallBack() {
                        if (currentTabIndex != index) {

                            img_navigation_home.setImageResource(R.mipmap.index_icon_01);
                            img_navigation_product.setImageResource(R.mipmap.index_icon_02);
                            img_navigation_integral.setImageResource(R.mipmap.index_icon_03_checked);
                            img_navigation_mine.setImageResource(R.mipmap.index_icon_04);

                            tv_navigation_home.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_product.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_integral.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlue_00a8f3));
                            tv_navigation_mine.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));

                            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                            trx.hide(fragments[currentTabIndex]);
                            if (!fragments[index].isAdded()) {
                                trx.add(R.id.navigation_content, fragments[index]);
                            }
                            trx.show(fragments[index]).commit();

                            currentTabIndex = index;

                        }

                    }

                });
                try {
                    ((FindFragment.CallBack)getAppCallBack(FindFragment.class)).onRefresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            case R.id.rl_navigation_mine:

                index = 3;

//
                LoginActivity.StartVerifyActivity(new LoginActivity.VerifyCallBack() {

                    @Override
                    public void onCallBack() {

                        if (currentTabIndex != index) {

                            img_navigation_home.setImageResource(R.mipmap.index_icon_01);
                            img_navigation_product.setImageResource(R.mipmap.index_icon_02);
                            img_navigation_integral.setImageResource(R.mipmap.index_icon_03);
                            img_navigation_mine.setImageResource(R.mipmap.index_icon_04_checked);

                            tv_navigation_home.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_product.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_integral.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlack99));
                            tv_navigation_mine.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textBlue_00a8f3));

                            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                            trx.hide(fragments[currentTabIndex]);
                            if (!fragments[index].isAdded()) {
                                trx.add(R.id.navigation_content, fragments[index]);
                            }

                            //实在没法确定调用时机时，可以用commitAllowingStateLoss 代替 commit ，commitAllowingStateLoss
                            // 在状态丢失时不会抛出任何异常，但也正因为如此在一些必须确保状态被保存的场合，
                            // 最好不要使用 commitAllowingStateLoss 方法。
                            trx.show(fragments[index]).commitAllowingStateLoss();

                            currentTabIndex = index;

                        }

                    }

                });


                try {
                    ((MineFragment.CallBack)getAppCallBack(MineFragment.class)).onRefresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;

        }

    }

    public interface OnClickProduct {
        void setOnClick();
        void setOnClickMine();
        void remove();
    }

    @Override
    public void onBackPressed() {

        timer = new Timer();
        if (isExit) {
            finish();
        } else {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            timerTask = new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    isExit = false;
                }
            };
            timer.schedule(timerTask, 2000);
        }
    }

//    private void requestPermission()
//    {
//        //判断Android版本是否大于23
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
//        {
//            if (ContextCompat.checkSelfPermission(NavigationActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(NavigationActivity.this, new String[]{Manifest.permission.CAMERA}, 1000);
//            }else {
//
//        }
////            else
////            {
////                callPhone();
////            }
//        }
//        else
//        {
////            callPhone();
//        }
//    }
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
//    {
//        switch (requestCode)
//        {
//            case  1000:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
//                {
////                    callPhone();
//                }
//                else
//                {
//                    // Permission Denied
//                    Toast.makeText(NavigationActivity.this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show();
//                }
//                break;
//            default:
//                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }

//    录音权限
    private void requestPermission(){
        Permissions4M.get(NavigationActivity.this)
                .requestForce(true)
                .requestPermission(Manifest.permission.RECORD_AUDIO)
                .requestCode(AUDIO_CODE)
                .requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                .request();
    }
    //    相机权限
    private void requestCameraPermission(){
        Permissions4M.get(NavigationActivity.this)
                .requestForce(true)
                .requestPermission(Manifest.permission.CAMERA)
                .requestCode(CAMERA_CODE)
                .requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                .request();
    }
//    回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        Permissions4M.onRequestPermissionsResult(NavigationActivity.this, requestCode, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //录音权限结果
    @PermissionsGranted(AUDIO_CODE)
    public void smsAndAudioGranted() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//            UtilToast.show("录音权限申请成功");
//        }
    }

    @PermissionsDenied(AUDIO_CODE)
    public void smsAndAudioDenied() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//            UtilToast.show("录音权限申请失败");
//        }
    }

    @PermissionsCustomRationale(AUDIO_CODE)
    public void smsAndAudioCustomRationale() {
        new AlertDialog.Builder(this)
                .setMessage("录音权限申请：\n我们需要您允许一直开启录音权限")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Permissions4M.get(NavigationActivity.this)
                                .requestForce(true)
                                .requestOnRationale()
                                .requestPermission(Manifest.permission.RECORD_AUDIO)
                                .requestCode(AUDIO_CODE)
                                .request();
                    }
                })
                .show();
    }
    //相机权限结果
    @PermissionsGranted(CAMERA_CODE)
    public void cameraGranted() {
//        UtilToast.show("相机权限授权成功 in fragment");
    }

    @PermissionsDenied(CAMERA_CODE)
    public void cameraDenied() {
//        UtilToast.show("相机权限授权失败 in fragment");
    }

    @PermissionsCustomRationale(CAMERA_CODE)
    public void cameraCustomRationale() {
        new AlertDialog.Builder(this)
                .setMessage("相机权限申请：\n我们需要您允许一直开启相机信息权限")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Permissions4M.get(NavigationActivity.this)
                                .requestForce(true)
                                .requestOnRationale()
                                .requestPermission(Manifest.permission.CAMERA)
                                .requestCode(CAMERA_CODE)
                                .request();
                    }
                })
                .show();
    }
    @PermissionsNonRationale({AUDIO_CODE,CAMERA_CODE})
    public void storageAndCallRationale(int code, final Intent intent) {
        switch (code) {
            case AUDIO_CODE:
                new AlertDialog.Builder(NavigationActivity.this)
                        .setMessage("用户您好，我们需要您允许一直开启录音权限\n请点击前往设置页面\n")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                break;

            case CAMERA_CODE:
                new AlertDialog.Builder(NavigationActivity.this)
                        .setMessage("读取相机权限申请：\n我们需要您一直开启相机权限\n")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(intent);

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                break;
            default:
                break;
        }
    }

    public class CallBack implements AppCallBack {

        public void onRefresh() {
            postLogintype.user_id = BaseApplication.BasePreferences.readUID();
            postLogintype.execute(NavigationActivity.this,false,0);

        }

    }
}
